package com.example.snashuitraverl.demos.controller;

import com.example.snashuitraverl.demos.common.BaseResponse;
import com.example.snashuitraverl.demos.common.ErrorCode;
import com.example.snashuitraverl.demos.common.ResultUtils;
import com.example.snashuitraverl.demos.domain.Do.AiDo;
import com.example.snashuitraverl.demos.domain.Request.ChatRequest;
import com.example.snashuitraverl.demos.exception.BusinessException;
import com.example.snashuitraverl.demos.service.ChataiService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@ApiOperation(value = "对接AI")
@RestController
@Slf4j
public class chatController {

    @Resource
    private ChataiService chataiService;

    @PostMapping("/chat")
    public BaseResponse<String> chatExchange(@RequestBody ChatRequest chatRequest) {
        String requestBody = chatRequest.getRequestBody();
        String openId = chatRequest.getOpenId();

        if (requestBody == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (StringUtils.isBlank(requestBody)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (StringUtils.isBlank(openId)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "为null");
        }
        return ResultUtils.success(chataiService.useChat(requestBody, openId), "成功");
    }

    @PostMapping("/chat/selectAll")
    public BaseResponse<Map<String, String>> selectAllchatExchange() {
        Map<String, String> stringStringMap = chataiService.selectAll();
        if (stringStringMap.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "您的openId没有查询到");
        }

        return ResultUtils.success(stringStringMap, "查询成功");
    }

    @GetMapping("/chat/selectByOpenId")
    public BaseResponse<Map<String, String>> selectByOpenIdchatExchange(@RequestParam String openId) {
        Map<String, String> stringStringMap = chataiService.selectopenId(openId);
        if (stringStringMap.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "您的openId没有查询到");
        }
        return ResultUtils.success(stringStringMap, "查询成功");
    }

    @GetMapping("/chat/selectByList")
    public BaseResponse<List<AiDo>> selectByListchatExchange(@RequestParam String openId) {
        List<AiDo> aiDoList = chataiService.selectByList(openId);
        if (aiDoList.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "您的openId没有查询到");
        }
        return ResultUtils.success(aiDoList, "查询成功");
    }

    @PostMapping("/chat/AI")
    public ResponseBodyEmitter handle(@RequestBody ChatRequest chatRequest) {
        // 创建 ResponseBodyEmitter 对象，无超时
        ResponseBodyEmitter responseBodyEmitter = new ResponseBodyEmitter(-1L);
        CompletableFuture.runAsync(() -> {
            try {
                String requestBody = chatRequest.getRequestBody();
                String openId = chatRequest.getOpenId();
                if (requestBody == null || StringUtils.isBlank(requestBody)) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR);
                }
                String aiMessage = chataiService.useChat(requestBody, openId);
//                for (int i = 0; i < aiMessage.length(); i += 50) {
//                    String partialMessage = aiMessage.substring(i, Math.min(i + 10, aiMessage.length()));
//                    responseBodyEmitter.send(partialMessage);
//                    responseBodyEmitter.send("\n");
//                    Thread.sleep(1000);
//                }
                responseBodyEmitter.send(aiMessage);
                // 完成发送
                responseBodyEmitter.complete();
            } catch (Exception e) {
                e.printStackTrace();
                // 异常处理
                responseBodyEmitter.completeWithError(e);

            }
        });
        // 返回 ResponseBodyEmitter 对象
        return responseBodyEmitter;
    }

//
//
//    @PostMapping("/chat/AI")
//    public ResponseBodyEmitter handle(@RequestBody ChatRequest chatRequest) {
//        // 创建 ResponseBodyEmitter 对象，无超时
//        ResponseBodyEmitter responseBodyEmitter = new ResponseBodyEmitter(-1L);
//
//        // 异步执行任务
//        CompletableFuture.runAsync(() -> {
//            try {
//                String requestBody = chatRequest.getRequestBody();
//                String openId = chatRequest.getOpenId();
//
//                // 参数校验
//                if (requestBody == null || StringUtils.isBlank(requestBody)) {
//                    throw new BusinessException(ErrorCode.PARAMS_ERROR);
//                }
//
//                // 调用业务逻辑，获取 AI 生成的完整消息
//                String aiMessage = chataiService.useChat(requestBody, openId);
//
//                // 调整 chunkSize，减少循环次数
//                int chunkSize = 500; // 每次发送500个字符
//                int totalLength = aiMessage.length();
//
//                // 如果消息较短，直接一次性发送出去
//                if (totalLength <= chunkSize) {
//                    responseBodyEmitter.send(aiMessage);
//                } else {
//                    // 将消息分段发送出去，减少循环带来的性能影响
//                    for (int i = 0; i < totalLength; i += chunkSize) {
//                        // 取出一部分字符串
//                        String partialMessage = aiMessage.substring(i, Math.min(i + chunkSize, totalLength));
//
//                        // 发送部分消息
//                        responseBodyEmitter.send(partialMessage);
//                    }
//                }
//                // 完成发送
//                responseBodyEmitter.complete();
//            } catch (Exception e) {
//                e.printStackTrace();
//                // 异常处理
//                responseBodyEmitter.completeWithError(e);
//            }
//        });
//        // 返回 ResponseBodyEmitter 对象
//        return responseBodyEmitter;
//    }


}
